<template>
	<SearchForm v-model:query-params="search" :config="searchConfig" @search="init" @reset="reset" />
	<el-button plain type="primary" @click="openDialog">新增</el-button>
	<el-table :data="tableData" border class="m-t-10px">
		<el-table-column type="index" align="center" label="#"></el-table-column>
		<el-table-column prop="id" label="ID" width="180" />
		<el-table-column prop="username" label="用户名" width="180" />
		<el-table-column prop="password" label="密码" width="180" />
		<el-table-column prop="roles" label="角色">
			<template #default="scope">
				<el-tag v-for="item in scope.row.roles" :key="item.id" class="ml-2px mr-2px">{{
					item.roleName
				}}</el-tag>
			</template>
		</el-table-column>
		<el-table-column prop="nickname" label="昵称" width="180" />
		<el-table-column prop="avatar" label="头像" width="180" align="center">
			<template #default="scope">
				<el-image :src="scope.row.avatar" style="width: 50px; height: 50px" v-if="scope.row.avatar"></el-image>
				<i-ep-user v-else></i-ep-user>
			</template>
		</el-table-column>
		<el-table-column fixed="right" label="操作" min-width="120">
			<template #default="scope">
				<!-- <el-button link type="primary"  @click="handleAssignRole(scope.row)"> 分配角色 </el-button> -->
				<el-button link type="primary" @click="edit(scope.row)">编辑</el-button>
				<el-button link type="primary" @click="del(scope.row)"> 删除 </el-button>
			</template>
		</el-table-column>
	</el-table>

	<Pagination
		v-show="total > 0"
		:total="total"
		v-model:page="search.page"
		v-model:limit="search.pageSize"
		@pagination="init"
	/>
	<el-dialog
		v-model="dialogFormVisible"
		:title="formData.id ? '编辑用户' : '添加用户'"
		width="800"
		:before-close="resetData"
	>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="resetData">取消</el-button>
				<el-button @click="handleSubmit(dformRef)" type="primary">确认</el-button>
			</div>
		</template>

		<dynamic-form ref="dformRef" :schemas="schemas" :rules="rules" v-model:formData="formData"> </dynamic-form>
	</el-dialog>
	<el-dialog v-model="assignRoleFormVisible" title="分配角色">
		<el-form ref="formRef" :model="assignRoleForm" label-width="auto">
			<el-form-item label="用户" prop="name">
				<el-input v-model="formData.username" placeholder="请输入" :disabled="true" />
			</el-form-item>
			<el-form-item label="角色" prop="zone">
				<el-select v-model="assignRoleForm.roleIds" multiple placeholder="Select">
					<el-option v-for="item in allRoleList" :key="item.id" :label="item.roleName" :value="item.id" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="assignRoleEnter" type="primary">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
// import { addUser, getList, delUser, updateUser, addTags } from "@/api/user1";
import type { UserInfo } from "@/api/user/type";
import { addUser, getList, delUser, updateUser, reqAssignRole } from "@/api/user";
import { reqGetRoleList } from "@/api/role";

import type { ConfigItem } from "@/components/SearchForm/type.ts";
import type { FormRules } from "element-plus";
// 搜索框
const search = reactive({
	username: "",
	page: 1,
	pageSize: 10,
});
const searchConfig: ConfigItem[] = [
	{
		label: "用户名称",
		prop: "username",
		type: "input",
	},
	// {
	// 	label: "状态",
	// 	prop: "status",
	// 	type: "select",
	// 	options: [
	// 		{ label: "启用", value: 1 },
	// 		{ label: "禁用", value: 0 },
	// 	],
	// },
	// {
	// 	label: "登录时间",
	// 	prop: "loginTime",
	// 	type: "daterange",
	// 	attrs: {
	// 		type: "daterange",
	// 		valueFormat: "YYYY-MM-DD HH:mm:ss",
	// 		rangeSeparator: "-",
	// 		startPlaceholder: "开始时间",
	// 		endPlaceholder: "结束时间",
	// 		defaultTime: [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)],
	// 	},
	// 	style: { width: "308px" },
	// },
];
/**
 * 初始化函数，用于异步获取列表数据并更新表格数据和总数
 */
const init = async () => {
	const res = await getList(search);
	if (res.code === 200) {
		tableData.value = res.data?.records ?? [];
		total.value = res.data?.total ?? 0;
	}
};
/**
 * 重置搜索状态
 * 将搜索栏的用户名清空，并初始化搜索状态。
 */
const reset = () => {
	search.username = "";
	console.log(search);
	init();
};

const formRef = ref();
//表单
const formData = reactive<UserInfo>({
	username: "",
	password: "",
	roles: [],
	nickname: "",
	id: 0,
	active: null,
});
import { FormSchema } from "@/components/DynamicForm/type";
const schemas: FormSchema[] = reactive([
	{
		field: "username",
		label: "用户名",
		component: "Input",
		required: true,
		rules: [{ required: true, message: "请输入用户名", trigger: "blur" }],
	},
	{
		field: "password",
		label: "密码",
		component: "Input",
		showPassword: true,
		rules: [{ required: true, message: "请输入密码", trigger: "blur" }],
	},
	{
		field: "nickname",
		label: "昵称",
		component: "Input",
		rules: [{ required: true, message: "请输入昵称", trigger: "blur" }],
	},
	{
		field: "active",
		label: "状态",
		component: "Select",
		options: [
			{ label: "正常", value: 1 },
			{ label: "停用", value: 0 },
		],
	},
	{
		field: "roles",
		label: "角色",
		component: "Select",
		componentProps: { multiple: true },
		options: [
			{ label: "正常", value: 1 },
			{ label: "停用", value: 0 },
		],
	},
	// {
	// 	field: "avatar",
	// 	label: "头像",
	// 	component: "Custom",
	// 	slot: "avatarUpload",
	// },
]);
const rules = reactive<FormRules<UserInfo>>({
	username: [
		{ required: true, message: "请输入用户名", trigger: "blur" },
		{ min: 3, max: 15, message: "Length should be 3 to 5", trigger: "blur" },
	],
	password: [
		{
			required: true,
			message: "请输入密码",
			trigger: "blur",
		},
	],
	nickname: [
		{
			required: true,
			message: "请输入昵称",
			trigger: "blur",
		},
	],
	active: [
		{
			required: true,
			message: "请选择状态",
			trigger: "change",
		},
	],
});

const dformRef = ref();
/**重置数据 */
const resetData = () => {
	formData.id = 0;
	dformRef.value.resetFields();
	dialogFormVisible.value = false;
	console.log(formData);
};

// 表格数据
const tableData = ref<any>([]);
const total = ref<number>(0);
const allRoleList = ref<any>([]);
const assignRoleFormVisible = ref<boolean>(false);
const assignRoleForm: Ref<{ roleIds: number[] }> = ref({
	roleIds: [],
});

// const handleAssignRole = async (row) => {
// 	//存储已有的用户信息
// 	Object.assign(formData, row);
// 	// 打开分配角色弹窗
// 	assignRoleFormVisible.value = true;
// 	// 请求角色列表
// 	const res = await getRoleList(row.id);
// 	allRoleList.value = res.data.allRoles;
// 	assignRoleForm.value.roleIds = res.data.assignRoles;
// };
//确定分配角色按钮事件
const assignRoleEnter = async () => {
	const res = await reqAssignRole(formData.id as number, assignRoleForm.value);
	if (res.code === 200) {
		ElMessage({
			type: "success",
			message: "分配成功",
		});
	}
	assignRoleFormVisible.value = false;
};

const doSubmit = async () => {
	if (formData.id) {
		await updateUser(formData);
		ElMessage({
			type: "success",
			message: "修改成功",
		});
	} else {
		const { id, ...data } = formData;
		console.log(id);
		await addUser(data);
		ElMessage({
			type: "success",
			message: "添加成功",
		});
	}
	resetData();
	init();
};

/**
 * 新增用户提交
 */
const handleSubmit = async (dformRef) => {
	// 校验表单数据
	if (!dformRef) return;
	dformRef
		.validate()
		.then(async () => {
			doSubmit();
			console.log("✅ 提交数据：");
		})
		.catch(() => {
			console.log("❌ 表单校验失败");
		});
};

/**点击编辑按钮触发 */
const edit = async (row) => {
	console.log(row);
	openDialog();
	// 回显表单数据中的角色信息
	nextTick(() => {
		formData.id = row.id;
		formData.username = row.username;
		formData.nickname = row.nickname;
		formData.active = row.active;
		formData.password = row.password;
		formData.roles = row.roles.map((item) => item.id);
	});
};

/**
 * 删除用户操作
 */
const del = async (row: { id: number }) => {
	ElMessageBox.confirm("确定删除该用户吗？", "警告", { type: "warning" })
		.then(async () => {
			await delUser(row.id);
			init();
			ElMessage({
				type: "success",
				message: "删除成功",
			});
		})
		.catch(() => {
			ElMessage({
				type: "info",
				message: "取消删除",
			});
		});
};

const dialogFormVisible = ref(false);
/**
 * 打开对话框
 */
const openDialog = () => {
	dialogFormVisible.value = true;
};

/**获取角色下拉数据 */
const getRoleOptions = async () => {
	const res = await reqGetRoleList();
	const roleOptions = res.data;
	const roleField = schemas.find((item) => item.field === "roles");
	if (roleField && roleOptions.length > 0) {
		roleField.options = roleOptions;
	}
};

/**监听dialogFormVisible */
watch(
	() => dialogFormVisible.value,
	async (newVal) => {
		if (!newVal) return;
		getRoleOptions();
	},
);

onMounted(() => {
	init();
});
</script>
